package com.gzy.studentsociety.web;
import com.gzy.studentsociety.dao.SocietyDao;
import com.gzy.studentsociety.dao.SocietyDaoImpl;
import com.gzy.studentsociety.dao.StudentDao;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Society;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

@WebServlet(name = "AddSocietyServlet", value = "/society/addSociety")
public class AddSocietyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");
        Society society = new Society();
        society.setSociety_intro(intro);
        society.setSociety_name(name);
        society.setSociety_status(1);
        //获取session中登录者为创建者
        String number = (String)(req.getSession().getAttribute("student"));
        StudentDao studentDao = new StudentDaoImpl();
        SocietyDao societyDao = new SocietyDaoImpl();
        try {
            society.setSociety_creator(studentDao.findByNumber(number).getStudentId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception",throwables);
            req.getRequestDispatcher("/WEB-INF/jsp/error.jsp");
        }
        society.setSociety_create_date(new Date());
        int result = -1;
        try {
            result = societyDao.insertSociety(society);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception",throwables);
            req.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(req,res);
        }
        res.sendRedirect("/studentSociety/society/mainIndex");
    }
}
